﻿using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

namespace Trentacular.SharePoint.Web.UI.WebParts
{
    [Guid("ebcd7a69-fc5c-452a-9639-6c07969e6991")]
    [XmlRoot(Namespace = "Trentacular.SharePoint.UI.WebParts.ControlWrapperWebPart")]
    [DefaultProperty("WrappedUserControlVirtualPath")]
    public class ControlWrapperWebPart : WebEditableWebPart, IControlWrapper
    {
        #region IControlWrapper Members

        /// <summary>
        /// When a WrappedUserControlVirtualPath is specified, this property holds
        /// the loaded user control after the CreateChildControls method has executed.
        /// </summary>
        public Control WrappedControl { get; private set; }

        #endregion

        /// <summary>
        /// Virtual path to a UserControl that this WebPart should wrap.  If specified,
        /// the user control will be loaded when CreateChildControls is invoked, set
        /// on the WrappedControl property, and added to the Controls collection.
        /// </summary>
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [Category("Behavior")]
        [WebDisplayName("UserControl Virtual Path")]
        [WebDescription("Specify the virtual path to the user control to load")]
        public virtual string WrappedUserControlVirtualPath { get; set; }

        [ConnectionProvider("Wrapped Control", "Control Provider", AllowsMultipleConnections = true)]
        public IControlWrapper ProvideControl()
        {
            return this;
        }

        [ConnectionConsumer("Wrapped Control", "Control Consumer", AllowsMultipleConnections = false)]
        public void ConsumeControl(IControlWrapper controlWrapper)
        {
            var controlConsumer = WrappedControl as IControlConsumer;
            if (controlConsumer != null)
                controlConsumer.ConsumeControl(controlWrapper.WrappedControl);
        }

        protected override void CreateChildControls()
        {
            if (!string.IsNullOrEmpty(WrappedUserControlVirtualPath))
            {
                try
                {
                    WrappedControl = Page.LoadControl(WrappedUserControlVirtualPath);
                    // WrappedControl.ID = "WrappedControl";
                    Controls.Add(WrappedControl);
                }
                catch (Exception e)
                {
                    Controls.Add(new LiteralControl(e.Message));
                }
            }

            base.CreateChildControls();
        }
    }
}
